#pragma once

#include <pthread.h>

namespace MutexModual
{
    class Mutex
    {
    public:
        // 互斥量不允许被拷贝，也不允许赋值
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;

        Mutex()
        {
            pthread_mutex_init(&_mutex, nullptr);
        }
        int Lock()
        {
            return pthread_mutex_lock(&_mutex);
        }
        int Unlock()
        {
            return pthread_mutex_unlock(&_mutex);
        }
        pthread_mutex_t *GetMutexPtr()
        {
            return &_mutex;
        }
        ~Mutex()
        {
            pthread_mutex_destroy(&_mutex);
        }

    private:
        pthread_mutex_t _mutex;
    };

    // 采用RAII风格，进行锁管理
    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex) : _mutex(mutex)
        {
            _mutex.Lock();
        }
        ~LockGuard()
        {
            _mutex.Unlock();
        }

    private:
        Mutex &_mutex;
    };
}